package com.ruoyi.work.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.work.domain.*;
import com.ruoyi.work.domain.vo.LoationUserQuery;
import com.ruoyi.work.domain.vo.LocationTrainQuery;
import com.ruoyi.work.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "救援任务-对外接口")
@RestController
@RequestMapping("/work/TbWorkOuter")
public class TbWorkOuterController extends BaseController {

    @Autowired
    private ITbWorkOrderService tbWorkOrderService;
    @Autowired
    private ITbWorkOrderUserService tbWorkOrderUserService;
    @Autowired
    private ITbEquTrainService tbEquTrainService;
    @Autowired
    private ITbLocationUserService tbLocationUserService;
    @Autowired
    private ITbLocationTrainService tbLocationTrainService;
    @Autowired
    private ITbWorkOrderEquService tbWorkOrderEquService;
    @Autowired
    private ITbWorkOrderGenericService tbWorkOrderGenericService;
    @Autowired
    private ITbWorkOrderMaterService tbWorkOrderMaterService;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation("新增救援任务")
    @PostMapping("/syncStart")
    public AjaxResult syncStart(@RequestBody TbWorkOrder tbWorkOrder) {
        boolean save = false;
        try {
            log.info(JSON.toJSONString(tbWorkOrder));
            if (tbWorkOrder != null) {
                String workNo = tbWorkOrder.getWorkNo();
                List<TbWorkOrder> orderList = tbWorkOrderService.lambdaQuery().eq(TbWorkOrder::getWorkNo, workNo).list();
                if (CollectionUtil.isNotEmpty(orderList)) {
                    TbWorkOrder workOrder = orderList.get(0);
                    tbWorkOrder.setId(workOrder.getId());
                    tbWorkOrder.setUpdateTime(new Date());
                    save = tbWorkOrderService.updateById(tbWorkOrder);

                    TbWorkOrderGeneric genericPlan = tbWorkOrder.getRescuePlan();
                    if (genericPlan != null) {
                        genericPlan.setWorkNo(workNo);
                        genericPlan.setUpdateTime(new Date());
                        save = tbWorkOrderGenericService.lambdaUpdate()
                                .set(TbWorkOrderGeneric::getDccContent, genericPlan.getDccContent())
                                .set(TbWorkOrderGeneric::getEmergencyTeamContent, genericPlan.getEmergencyTeamContent())
                                .set(TbWorkOrderGeneric::getHandlePrinciple, genericPlan.getHandlePrinciple())
                                .set(TbWorkOrderGeneric::getRepairUserContent, genericPlan.getRepairUserContent())
                                .set(TbWorkOrderGeneric::getOthenEamContent, genericPlan.getOthenEamContent())
                                .eq(TbWorkOrderGeneric::getWorkNo, workNo).update();
                    }
                    List<TbWorkOrderUser> userList = tbWorkOrder.getUserList();
                    if (CollectionUtil.isNotEmpty(userList)) {
                        for (TbWorkOrderUser orderUser : userList) {
                            orderUser.setUpdateTime(new Date());
                            orderUser.setStatus("1");
                            List<TbWorkOrderUser> list = tbWorkOrderUserService.lambdaQuery()
                                    .eq(TbWorkOrderUser::getWorkNo, workNo)
                                    .eq(TbWorkOrderUser::getUserNo, orderUser.getUserNo()).list();
                            if (list.size() > 0) {
                                String id = list.get(0).getId();
                                orderUser.setId(id);
                            } else {
                                orderUser.setWorkNo(workNo);
                                orderUser.setCreateTime(new Date());
                                orderUser.setUpdateTime(new Date());
                                orderUser.setStatus("1");
                            }
                        }
                        save = tbWorkOrderUserService.saveOrUpdateBatch(userList);
                    }
                    List<TbWorkOrderMater> materList = tbWorkOrder.getMaterList();
                    if (CollectionUtil.isNotEmpty(materList)) {
                        for (TbWorkOrderMater mater : materList) {
                            mater.setUpdateTime(new Date());
                            List<TbWorkOrderMater> list = tbWorkOrderMaterService.lambdaQuery()
                                    .eq(TbWorkOrderMater::getWorkNo, workNo).list();
                            if (list.size() > 0) {
                                String id = list.get(0).getId();
                                mater.setId(id);
                            } else {
                                mater.setWorkNo(workNo);
                                mater.setCreateTime(new Date());
                                mater.setUpdateTime(new Date());
                            }
                        }
                        save = tbWorkOrderMaterService.saveOrUpdateBatch(materList);
                    }

                    List<TbWorkOrderEqu> equlist = tbWorkOrder.getEquList();
                    if (CollectionUtil.isNotEmpty(equlist)) {

                        for (TbWorkOrderEqu orderEqu : equlist) {
                            orderEqu.setUpdateTime(new Date());
                            List<TbWorkOrderEqu> list = tbWorkOrderEquService.lambdaQuery()
                                    .eq(TbWorkOrderEqu::getWorkNo, workNo).list();
                            if (list.size() > 0) {
                                String id = list.get(0).getId();
                                orderEqu.setId(id);
                            } else {
                                orderEqu.setWorkNo(workNo);
                                orderEqu.setCreateTime(new Date());
                                orderEqu.setCreateTime(new Date());
                            }
                        }
                        save = tbWorkOrderEquService.saveOrUpdateBatch(equlist);
                    }
                } else {
                    String[] split = tbWorkOrder.getTrainNo().split(",");
                    List<TbEquTrain> equTrains = tbEquTrainService.lambdaQuery().in(TbEquTrain::getTrainNo, split).list();
                    if (CollectionUtil.isNotEmpty(equTrains)) {
                        String equNos = equTrains.stream().map(x -> x.getEquNo()).collect(Collectors.joining(","));
                        tbWorkOrder.setEquNo(equNos);
                        tbWorkOrder.setCreateTime(new Date());
                        tbWorkOrder.setUpdateTime(new Date());
                        tbWorkOrder.setStatus("1");
                        save = tbWorkOrderService.save(tbWorkOrder);

                        TbWorkOrderGeneric genericPlan = tbWorkOrder.getRescuePlan();
                        if (genericPlan != null) {
                            genericPlan.setWorkNo(workNo);
                            genericPlan.setCreateTime(new Date());
                            genericPlan.setUpdateTime(new Date());
                            save = tbWorkOrderGenericService.save(genericPlan);
                        }
                        List<TbWorkOrderUser> userList = tbWorkOrder.getUserList();
                        if (CollectionUtil.isNotEmpty(userList)) {
                            userList.forEach(x -> {
                                x.setStatus("1");
                                x.setWorkNo(workNo);
                            });
                            save = tbWorkOrderUserService.saveBatch(userList);
                        }
                        List<TbWorkOrderMater> materList = tbWorkOrder.getMaterList();
                        if (CollectionUtil.isNotEmpty(materList)) {
                            materList.forEach(x -> {
                                x.setWorkNo(workNo);
                                x.setCreateTime(new Date());
                                x.setUpdateTime(new Date());
                            });
                            save = tbWorkOrderMaterService.saveBatch(materList);
                        }
                        List<TbWorkOrderEqu> equlist = tbWorkOrder.getEquList();
                        if (CollectionUtil.isNotEmpty(equlist)) {
                            equlist.forEach(x -> {
                                x.setWorkNo(workNo);
                                x.setCreateTime(new Date());
                                x.setUpdateTime(new Date());
                            });
                            save = tbWorkOrderEquService.saveBatch(equlist);
                        }

                        if (save) {
                            for (TbEquTrain train : equTrains) {
                                redisCache.deleteObject(CacheConstants.WORK_NO + train.getEquNo());
                                redisCache.setCacheObject(CacheConstants.WORK_NO + train.getEquNo(), tbWorkOrder);
                            }
                            redisCache.setCacheObject(tbWorkOrder.getWorkNo(), tbWorkOrder.getWorkNo());
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return save ? AjaxResult.success() : AjaxResult.error();
    }

    @ApiOperation("结束救援任务")
    @PostMapping("/syncEnd")
    public AjaxResult syncEnd(@RequestBody String data) {
        JSONObject object = JSONObject.parseObject(data);
        List<TbWorkOrder> orderList = tbWorkOrderService.lambdaQuery().eq(TbWorkOrder::getWorkNo, object.getString("workNo")).list();
        if (CollectionUtil.isNotEmpty(orderList)) {
            TbWorkOrder tbWorkOrder = orderList.get(0);
            tbWorkOrder.setStatus("2");
            tbWorkOrder.setUserName(object.getString("userName"));
            tbWorkOrder.setUpdateTime(new Date());
            boolean b = tbWorkOrderService.updateById(tbWorkOrder);
            if (b) {
                String[] split = orderList.get(0).getTrainNo().split(",");
                List<TbEquTrain> equTrains = tbEquTrainService.lambdaQuery().in(TbEquTrain::getTrainNo, split).list();
                for (TbEquTrain train : equTrains) {
                    redisCache.deleteObject(CacheConstants.WORK_NO + train.getEquNo());
                }
                redisCache.deleteObject(tbWorkOrder.getWorkNo());

                List<TbWorkOrderUser> userList = tbWorkOrderUserService.lambdaQuery().eq(TbWorkOrderUser::getWorkNo, tbWorkOrder.getWorkNo()).list();
                if (CollectionUtil.isNotEmpty(userList)){
                    for (TbWorkOrderUser user : userList){
                        redisCache.deleteObject(user.getUserNo());
                    }
                }

                tbWorkOrderUserService.updateByWorkNo(tbWorkOrder.getWorkNo());
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("任务编号不存在");
    }


    @ApiOperation("救援车辆台账")
    @PostMapping("/syncTrain")
    public AjaxResult syncUserTeam(@RequestBody String data) {
        System.out.println(data);
        List<TbEquTrain> equTrains = JSONArray.parseArray(data, TbEquTrain.class);
        if (CollectionUtil.isNotEmpty(equTrains)) {
            for (TbEquTrain equTrain : equTrains) {
                equTrain.setCreateTime(new Date());
                List<TbEquTrain> list = tbEquTrainService.lambdaQuery().eq(TbEquTrain::getTrainNo, equTrain.getTrainNo()).list();
                if (list.size() > 0) {
                    equTrain.setUpdateTime(new Date());
                    equTrain.setId(list.get(0).getId());
                }
            }
        }

        boolean b = tbEquTrainService.saveOrUpdateBatch(equTrains);
        return b ? AjaxResult.success() : AjaxResult.error("任务编号不存在");
    }


    @ApiOperation("分页获取车辆定位信息")
    @PostMapping("/getPageTrainLocation")
    public AjaxResult getPageTrainLocation(@RequestBody LocationTrainQuery entity) {

        Integer pageNo = entity.getPageNo();
        if (pageNo == 0 || pageNo == null) {
            pageNo = 1;
        }

        Integer pageSize = entity.getPageSize();
        if (pageNo == 0 || pageNo == null) {
            pageSize = 100;
        } else if (pageSize > 1000) {
            pageSize = 1000;
        }

        QueryWrapper wrapper = new QueryWrapper();
        TbLocationTrain locationTrain = new TbLocationTrain();

        if (StringUtils.isNotEmpty(entity.getTrainNo())) {
            locationTrain.setTrainNo(entity.getTrainNo());
        }

        if (StringUtils.isNotEmpty(entity.getWorkNo())) {
            locationTrain.setWorkNo(entity.getWorkNo());
        }

        wrapper.setEntity(locationTrain);

        if (StringUtils.isNotEmpty(entity.getStartTime()) && StringUtils.isNotEmpty(entity.getEndTime())) {
            wrapper.between("last_time", entity.getStartTime(), entity.getEndTime());
        }

        Page<TbLocationTrain> page = new Page<>(pageNo, pageSize);
        PageHelper.startPage(pageNo, pageSize, "id asc");
        Page<TbLocationTrain> pageList = tbLocationTrainService.page(page, wrapper);
        pageList.setTotal(new PageInfo(pageList.getRecords()).getTotal());
        return AjaxResult.success(pageList);
    }


    @ApiOperation("不分页获取车辆定位信息")
    @PostMapping("/getTrainLocation")
    public AjaxResult getTrainLocation(@RequestBody LocationTrainQuery entity) {

        QueryWrapper wrapper = new QueryWrapper();
        TbLocationTrain locationTrain = new TbLocationTrain();

        if (StringUtils.isNotEmpty(entity.getTrainNo())) {
            locationTrain.setTrainNo(entity.getTrainNo());
        }

        if (StringUtils.isNotEmpty(entity.getWorkNo())) {
            locationTrain.setWorkNo(entity.getWorkNo());
        }

        wrapper.setEntity(locationTrain);

        if (StringUtils.isNotEmpty(entity.getStartTime()) && StringUtils.isNotEmpty(entity.getEndTime())) {
            wrapper.between("last_time", entity.getStartTime(), entity.getEndTime());
        }

        List<TbLocationTrain> pageList = tbLocationTrainService.list(wrapper);
        return AjaxResult.success(pageList);
    }

    @ApiOperation("分页获取人员定位信息")
    @PostMapping("/getPageUserLocation")
    public AjaxResult getPageUserLocation(@RequestBody LoationUserQuery entity) {

        Integer pageNo = entity.getPageNo();
        if (pageNo == 0 || pageNo == null) {
            pageNo = 1;
        }

        Integer pageSize = entity.getPageSize();
        if (pageNo == 0 || pageNo == null) {
            pageSize = 100;
        } else if (pageSize > 1000) {
            pageSize = 1000;
        }

        QueryWrapper wrapper = new QueryWrapper();
        TbLocationUser locationUser = new TbLocationUser();
        if (StringUtils.isNotEmpty(entity.getUserNo())) {
            locationUser.setUserNo(entity.getUserNo());
        }
        if (StringUtils.isNotEmpty(entity.getUserName())) {
            locationUser.setUserName(entity.getUserName());
        }

        if (StringUtils.isNotEmpty(entity.getWorkNo())) {
            locationUser.setWorkNo(entity.getWorkNo());
        }

        wrapper.setEntity(locationUser);

        if (StringUtils.isNotEmpty(entity.getStartTime()) && StringUtils.isNotEmpty(entity.getEndTime())) {
            wrapper.between("create_time", entity.getStartTime(), entity.getEndTime());
        }

        Page<TbLocationUser> page = new Page<>(pageNo, pageSize);
        PageHelper.startPage(pageNo, pageSize, "id asc");
        Page<TbLocationUser> pageList = tbLocationUserService.page(page, wrapper);
        pageList.setTotal(new PageInfo(pageList.getRecords()).getTotal());

        return AjaxResult.success(pageList);
    }


    @ApiOperation("不分页获取人员定位信息")
    @PostMapping("/getUserLocation")
    public AjaxResult getUserLocation(@RequestBody LoationUserQuery entity) {

        QueryWrapper wrapper = new QueryWrapper();
        TbLocationUser locationUser = new TbLocationUser();
        if (StringUtils.isNotEmpty(entity.getUserNo())) {
            locationUser.setUserNo(entity.getUserNo());
        }
        if (StringUtils.isNotEmpty(entity.getUserName())) {
            locationUser.setUserName(entity.getUserName());
        }

        if (StringUtils.isNotEmpty(entity.getWorkNo())) {
            locationUser.setWorkNo(entity.getWorkNo());
        }

        wrapper.setEntity(locationUser);

        if (StringUtils.isNotEmpty(entity.getStartTime()) && StringUtils.isNotEmpty(entity.getEndTime())) {
            wrapper.between("create_time", entity.getStartTime(), entity.getEndTime());
        }

        List<TbLocationUser> pageList = tbLocationUserService.list(wrapper);

        return AjaxResult.success(pageList);
    }
}
